import socket,select
add = ('127.0.0.1',7890)
add = ('154.221.19.38',7890)
import time
msgLen = 1300
msg = b'a'*msgLen
maxSock = 40

import sys
if len(sys.argv)>=2:
    maxSock = int(sys.argv[1])
if len(sys.argv)>=3:
    msgLen = int(sys.argv[2])
print (maxSock,msgLen)

timeoutTime = 0.3
co = 0
ne = 0
seCo = 0
newConn = 0
ti = uTime = time.monotonic()
sockMap = {}
pollMap = {}
dataTimeL = []
connTimeL = []

while True:
    tt = time.monotonic()
    while len(sockMap)+len(pollMap)<maxSock:
        ne += 1
        s = socket.socket()
        s.setblocking(False)          
        s.connect_ex(add)
        pollMap[s] = tt
    rl = list(sockMap.keys())
    wl = list(pollMap.keys())
    el = list(pollMap.keys())    
    rl ,wl,el = select.select(rl,wl,el,0.1)    
    for one in rl:        
        try:
            r = one.recv(10000)
            if  len(r)!=len(msg):
                print ('error')
                one.close()
                del sockMap[one]
                continue
            co +=1
            dataTimeL.append(tt-sockMap[one])
            sockMap[one] = tt
            one.send(msg)  
            seCo += 1
        except Exception as e:
            one.close()
            del sockMap[one]
            print (e)  
            
    for one in wl:
        try:
            connTimeL.append(tt-pollMap[one])
            del pollMap[one]
            sockMap[one]=tt
            one.send(msg) 
            seCo += 1
            newConn += 1
        except Exception as e:
            print (e)  
            one.close()
            del sockMap[one]
    for one in el:
        del pollMap[one]
            
    if uTime+0.1<tt:
        uTime = tt
        for k in list(sockMap.keys()):
            if sockMap[k]+timeoutTime<tt:
                del sockMap[k]
                k.close()  
        for k in list(pollMap.keys()):
            if pollMap[k]+timeoutTime<tt:
                del pollMap[k]
                k.close()     
                
    if time.monotonic()-ti>1:
        ti = time.monotonic()
        if not dataTimeL:
            a,b,c = -1,-1,-1
        else:
            a,b,c = min(dataTimeL),max(dataTimeL),sum(dataTimeL)/len(dataTimeL)
        if not connTimeL:
            d,e,f = -1,-1,-1
        else:
            d,e,f = min(connTimeL),max(connTimeL),sum(connTimeL)/len(connTimeL)    
        st = '%1.1f %s %s %s %s %1.2f %1.2f %1.2f %1.2f %1.2f %1.2f'%\
              (ti,ne,co*len(msg),seCo,newConn,a,b,c,d,e,f)            
        print(st)        
        ne = co = seCo = newConn =0
        dataTimeL = []
        connTimeL = []     


